<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" src="/node/grid/dependents/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/node/grid/dlshouwen.grid.js"></script>
    <script type="text/javascript" src="/node/grid/i18n/zh-cn.js"></script>
    <script type="text/javascript" src="/node/fileupload/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="/node/fileupload/jquery.iframe-transport.js"></script>
    <script type="text/javascript" src="/node/fileupload/jquery.fileupload.js"></script>

    <!-- bootstrap -->
    <script type="text/javascript" src="/node/grid/dependents/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/node/grid/dependents/bootstrap/css/bootstrap.min.css"/>

    <!-- font-awesome -->
    <link rel="stylesheet" type="text/css" href="/node/grid/dependents/fontAwesome/css/font-awesome.min.css" media="all"/>

    <link rel="stylesheet" href="/node/fileupload/jquery.fileupload.css">
    <link rel="stylesheet" type="text/css" href="/node/grid/dlshouwen.grid.min.css"/>

    <!-- excel -->
    <script lang="javascript" src="/node/xlsx.full.min.js"></script>

    <!-- filesaver -->
    <script lang="javascript" src="/node/FileSaver.min.js"></script>
</head>
<body>
    <div id="div_operate" style="text-align:right">
        <form id="fileuploadForm" action="'/node/excelImport'" method="POST" enctype="multipart/form-data" class="" novalidate="novalidate">
            <input type="hidden" name="affa_id" id="affa_id" />
            <input type="hidden" name="flow_id" id="flow_id" />
            <input type="hidden" name="regitem_id" id="regitem_id" />
            <button id="templDownload" type="button" class="btn btn-xs"><i class="fa fa-download"></i> 模版下载</button>
            <span class="btn fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>选择文件...</span>
                <input id="file" type="file" multiple>
            </span>
            <button id="btnDelete" type="button" class="btn btn-xs btn-danger" ><i class="fa fa-trash-o"></i>  删除</button>
            <br>
            <!-- The global progress bar -->
            <span id="upload_progress"></span>
            <!-- The container for the uploaded files -->
        </form>
    </div>
    <div id="main">
        <div id="gridContainer" class="dlshouwen-grid-container"></div>
        <div id="gridToolBarContainer" class="dlshouwen-grid-toolbar-container"></div>
    </div>
</body>
<script type="text/javascript">
    //获取url中的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
    var grid;
    var gridColumns;
    $(function(){
        // 获取url内flow_id
        var flow_id = getUrlParam('flow_id'),
            affa_id = getUrlParam('affa_id'),
            regitem_id = getUrlParam('regitem_id');
        $('#affa_id').val(affa_id);
        $('#flow_id').val(flow_id);
        $('#regitem_id').val(regitem_id);
        // 获取列设置
        $.getJSON('/node/excel/gridColumns', {flow_id: flow_id}, function(data){
            if (data.result === 'succeed' && data.data.length > 0) {
                gridColumns = data.data;
                console.log(JSON.stringify(gridColumns));
                var gridOption = {
                    lang : 'zh-cn',
                    ajaxLoad : false,
                    check : true,
                    datas : [],
                    checkWidth : 40,
                    columns : gridColumns,
                    gridContainer : 'gridContainer',
                    toolbarContainer : 'gridToolBarContainer',
                    tools : '',
                    pageSize : 10,
                    pageSizeLimit : [10, 20, 50]
                };
                loadData(affa_id, flow_id, regitem_id, function(data){
                    gridOption.datas = data;
                    grid = $.fn.dlshouwen.grid.init(gridOption);
                    grid.load();
                });
                // 模版导出按钮
                $('#templDownload').click(function(){
                    var output = {};
                    gridColumns.forEach(function(e){
                        output[e.cell] = {
                            v: e.title
                        };
                    });
                    var ref = gridColumns[0].cell + ':' + gridColumns[gridColumns.length-1].cell;
                    var wb = {
                        SheetNames: ['sheet1'],
                        Sheets: {
                            'sheet1': Object.assign({}, output, { '!ref': ref })
                        }
                    }
                    var wopts = { bookType:'xlsx', bookSST:false, type:'binary' };
                    var wbout = XLSX.write(wb,wopts);
                    saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "模版.xlsx");
                });
            } else {
                alert('未查询到列数据!');
                return false
            }
        });
        var type = getUrlParam('type');
        if (type === 'edit') {
            $('#div_operate').hide();
            return;
        }
        // 绑定上传功能
        $('#fileuploadForm').fileupload({
            url: '/node/excel/excelImport',
            dataType: 'json',
            done: function(e, data) {
                var result = data.result.result;
                if(result === 'succeed'){
                    $('#upload_progress').html('');
                    loadData(affa_id, flow_id, regitem_id, function(data){
                        grid.originalDatas = data;
                        grid.reload(true);
                    });
                } else {
                    $('#upload_progress').html('上传失败');
                }
            },
            progressall: function(e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#upload_progress').html(progress + '%');
            }
        }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

        // 绑定删除按钮点击事件
        $('#btnDelete').click(function(){
            var ids = grid.getCheckedRecords().map(function(element){
                return element.id;
            });
            $.getJSON('/node/excel/remove', {ids: ids.join(',')}, function(data){
                if (data.result === 'succeed') {
                    grid.originalDatas = grid.originalDatas.filter(function(element){
                        return ids.indexOf(element.id) < 0;
                    });
                    grid.reload(true);
                }
            });
        });
    });
    // 加载数据    
    function loadData(affa_id, flow_id, regitem_id, callback){
        var url,
            params;
        if (affa_id !=undefined && affa_id != '') {
            url = '/node/excel/loadAll_affaid';
            params = {affa_id: affa_id};
        } else if (flow_id != undefined && flow_id != '' && regitem_id != '' && regitem_id != '') {
            url = '/node/excel/loadAll_flowid';
            params = {flow_id: flow_id, regitem_id: regitem_id};
        } else {
            return;
        }
        $.getJSON(url, params, function(data){
            if (data.result === 'succeed') {
                callback(data.data);
            }
        });
    }
</script>
</html>